<?php

namespace app\api\controller;

use app\api\extend\Common;
use think\facade\Db;

class HomeMuserfriend extends Common
{
    public function add() {
        // $res = $this->check_params();
        // if (!empty($res)) return $res;
        $res = Db::name('home_muserfriend')->where([
            'friend_id'=>$this->params['friend_id'],
             'muser_id'=>$this->request->auth['userId']   
        ])->find();
        if (!empty($res)) {
            return  $this->return_msg(201,'朋友已存在');
        }
        $data1 = array_merge($this->params,['muser_id'=>$this->request->auth['userId'],'add_time'=>date('Y:m:d H:i:s')]);
         $res = Db::name('home_muserfriend')->insert($data1);
        if (!$res){
            return $this->return_msg(400,'添加失败');
        }
        $user = Db::name('home_muser')->where('id',$this->request->auth['userId'])->find();
        $data2 = [
            'friend_id'=>$this->request->auth['userId'],
            'muser_id'=>$this->params['friend_id'],
            'add_time'=>date('Y:m:d H:i:s')
        ];
        $res = Db::name('home_muserfriend')->insert($data2);
        if (!$res){
            return $this->return_msg(400,'添加失败');
        }
        return $this->return_msg(200,'添加成功');
    }

    public function list() {
        $where = [
           [ 'a.muser_id','=',$this->request->auth['userId']],
        ];
        
        $res1 = Db::name('home_muserfriend')
        ->alias('a')
        ->join('home_muser b','b.id = a.friend_id')
        ->where($where)
        ->field('b.name as friend_name,b.id as friend_id,b.avatar_image as friend_avatar_image')
        ->select()->toArray();

        $userId = $this->request->auth['userId'];
        $friendIds = [];
        foreach ($res1 as $v) {
            $friendIds[] = $v['friend_id'];
        }
        $friendIds[] = intval($userId);
        
        $res2 = Db::name('home_chartmessages')
            ->whereIn('user_id', $friendIds)
            ->whereIn('friend_id', $friendIds)
            ->field('friend_id,max(timestamp) as timestamp')
            ->group('friend_id')            
            ->select()->toArray();

        // var_dump($res2);

        $res3 = [];
        foreach ($res2 as $v) {
            $res3[] = $v['timestamp'];
        }
        // var_dump($res3);

        $res4 = Db::name('home_chartmessages')
        ->whereIn('timestamp',$res3)
        ->field('friend_id,message,message_type,timestamp')
        ->select()->toArray();

        // var_dump($res4);

        $result = [];
        for ($i = 0; $i < count($res4); $i++) {
           for ($j = 0; $j < count($res1); $j++) {
               if ($res4[$i]['friend_id'] == $res1[$j]['friend_id']) {
                    $result[] = array_merge($res1[$j],$res4[$i]);
                }
           }
        }

        $res = array_reverse($result);

        return $this->return_msg(200,'获取成功',$res);
    }

}